

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
  <title>二分&amp;三分 - violet apricity</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10.4.0/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.9","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>violet apricity</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="二分&三分">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-04-18 15:45" pubdate>
        2021年4月18日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      15
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">二分&amp;三分</h1>
            
            <div class="markdown-body">
              <h1 id="二分-amp-三分"><a href="#二分-amp-三分" class="headerlink" title="二分&amp;三分"></a>二分&amp;三分</h1><h2 id="二分"><a href="#二分" class="headerlink" title="二分"></a>二分</h2><h3 id="简介："><a href="#简介：" class="headerlink" title="简介："></a>简介：</h3><p>二分查找（英语：binary search），也称折半搜索（英语：half-interval search）、对数搜索（英语：logarithmic search），是用来在一个<strong>有序</strong>序列中查找某一元素的算法。</p>
<p><strong>二分是一种细节很多实现很容易出错的搜索算法。</strong></p>
<h3 id="原理："><a href="#原理：" class="headerlink" title="原理："></a>原理：</h3><p>以在一个升序数组中查找一个数为例。</p>
<p>它每次考察数组当前部分的中间元素，如果中间元素刚好是要找的，就结束搜索过程；如果中间元素小于所查找的值，那么左侧的只会更小，不会有所查找的元素，只需到右侧查找；如果中间元素大于所查找的值同理，只需到左侧查找。</p>
<p>这种方法每次可以排除一半的答案，可以以对数形式减少复杂度。</p>
<h3 id="性质"><a href="#性质" class="headerlink" title="性质"></a>性质</h3><h4 id="时间复杂度"><a href="#时间复杂度" class="headerlink" title="时间复杂度"></a>时间复杂度</h4><p>二分查找的最优时间复杂度为 O(1)。</p>
<p>二分查找的平均时间复杂度和最坏时间复杂度均为O(log n) 。因为在二分搜索过程中，算法每次都把查询的区间减半，所以对于一个长度为n 的数组，至多会进行O(log n) 次查找。</p>
<h4 id="空间复杂度"><a href="#空间复杂度" class="headerlink" title="空间复杂度"></a>空间复杂度</h4><p>迭代版本的二分查找的空间复杂度为O(1) 。</p>
<p>递归（无尾调用消除）版本的二分查找的空间复杂度为O(log n) 。</p>
<h3 id="代码实现："><a href="#代码实现：" class="headerlink" title="代码实现："></a>代码实现：</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">binary_search</span><span class="hljs-params">(<span class="hljs-keyword">int</span> start, <span class="hljs-keyword">int</span> end, <span class="hljs-keyword">int</span> key)</span> </span>&#123;<br>  <span class="hljs-keyword">int</span> ret = <span class="hljs-number">-1</span>;  <span class="hljs-comment">// 未搜索到数据返回-1下标</span><br>  <span class="hljs-keyword">int</span> mid;<br>  <span class="hljs-keyword">while</span> (start &lt;= end) &#123;<br>    mid = start + ((end - start) &gt;&gt; <span class="hljs-number">1</span>);  <span class="hljs-comment">// 直接平均可能会溢出，所以用这个算法</span><br>    <span class="hljs-keyword">if</span> (arr[mid] &lt; key)<br>      start = mid + <span class="hljs-number">1</span>;<br>    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (arr[mid] &gt; key)<br>      end = mid - <span class="hljs-number">1</span>;<br>    <span class="hljs-keyword">else</span> &#123;  <span class="hljs-comment">// 最后检测相等是因为多数搜索情况不是大于就是小于</span><br>      ret = mid;<br>      <span class="hljs-keyword">break</span>;<br>    &#125;<br>  &#125;<br>  <span class="hljs-keyword">return</span> ret;  <span class="hljs-comment">// 单一出口</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="STL"><a href="#STL" class="headerlink" title="STL"></a>STL</h3><p>C++ 标准库中实现了查找<strong>首个不小于给定值</strong>的元素的函数 <a target="_blank" rel="noopener" href="https://zh.cppreference.com/w/cpp/algorithm/lower_bound"><code>std::lower_bound</code></a> 和查找<strong>首个大于给定值</strong>的元素的函数 <a target="_blank" rel="noopener" href="https://zh.cppreference.com/w/cpp/algorithm/upper_bound"><code>std::upper_bound</code></a>，二者均定义于头文件 <code>&lt;algorithm&gt;</code> 中。</p>
<p>二者均采用二分实现，所以调用前必须保证元素有序。</p>
<h3 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h3><h4 id="最大值最小化-最小值最大化"><a href="#最大值最小化-最小值最大化" class="headerlink" title="最大值最小化/最小值最大化"></a>最大值最小化/最小值最大化</h4><p>注意，这里的有序是<strong>广义的有序</strong>，如果一个数组中的左侧或者右侧都满足某一种条件，而另一侧都不满足这种条件，也可以看作是一种有序（如果把满足条件看做1 ，不满足看做 0，至少对于这个条件的这一维度是有序的）。换言之，二分搜索法可以用来查找<strong>满足某种条件的最大（最小）的值。</strong></p>
<p>要求满足某种条件的<strong>最大值的最小可能情况（最大值最小化）</strong>，首先的想法是从小到大<strong>枚举</strong>这个作为答案的「<strong>最大值</strong>」，然后去<strong>判断是否合法</strong>。若答案<strong>单调</strong>，就可以使用二分搜索法来更快地找到答案。因此，要想使用二分搜索法来解这种「最大值最小化」的题目，需要满足以下三个条件：</p>
<ol>
<li>答案在一个<strong>固定区间</strong>内；</li>
<li>可能查找一个符合条件的值不是很容易，但是要求能<strong>比较容易地判断某个值是否是符合条件</strong>的；</li>
<li><strong>可行解对于区间满足一定的单调性</strong>。换言之，如果 是符合条件的，那么有 x+1或者 x-1也符合条件。（这样下来就满足了上面提到的单调性）</li>
</ol>
<p>当然，最小值最大化是同理的。</p>
<h4 id="二分答案"><a href="#二分答案" class="headerlink" title="二分答案"></a>二分答案</h4><p>当一个问题的答案有限（或者很少），那么我们可以枚举每个答案，然后判断答案是否可行。</p>
<p>这是基于一些问题<strong>判断一个答案是否合适</strong>比<strong>找到一个合适答案</strong>来的容易。</p>
<p>因此若答案满足单调性，则满足使用二分法的条件。把这里的枚举换成二分，就变成了“二分答案”。</p>
<h2 id="三分"><a href="#三分" class="headerlink" title="三分"></a>三分</h2><h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p>在区间内用两个mid将<strong>区间分成三份</strong>，这样的查找算法称为三分查找,也就是三分法，三分法常</p>
<p>用于求解<strong>单峰函数的最值</strong>。</p>
<p>还有一种理解，即在二分查找的基础上，在左区间或者右区间上<strong>再进行一次二分</strong>。</p>
<h3 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h3><p>1.先将区间三分,每个区间的长度为1/3(right-left)</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs c++">mid1=left+(right-left)/<span class="hljs-number">3</span>;<br>mid2=right-(right-left)/<span class="hljs-number">3</span>;<br></code></pre></td></tr></table></figure>

<p>2.比较mid1和mid2谁更靠近极值，如果mid1更靠近极值，右区间改为mid2,否则左区间改为mid1(后面的代码都是以求最大值即凸函数为例）</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">calc</span>(mid1)&lt;<span class="hljs-built_in">calc</span>(mid2))<br>    left=mid1;<br><span class="hljs-keyword">else</span><br>    right=mid2;<br></code></pre></td></tr></table></figure>

<p>3.重复1,2过程，直到不满足left+eps&lt;right,也就是找到最值</p>
<p>算法模板</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> eps 10e-6</span><br><span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">cal</span><span class="hljs-params">()</span> </span>&#123;&#125; <span class="hljs-comment">//计算题目所需要的值</span><br><span class="hljs-keyword">while</span>(l+eps&lt;r)<br>&#123;<br>    m1=l+(r-l)/<span class="hljs-number">3</span>;<br>    m2=r-(r-l)/<span class="hljs-number">3</span>;<br>    v1=<span class="hljs-built_in">cal</span>(m1);<br>    v2=<span class="hljs-built_in">cal</span>(m2);<br>    <span class="hljs-keyword">if</span>(v1&lt;v2)l=m1;<br>    <span class="hljs-keyword">else</span> r=m2;<br>&#125;<br></code></pre></td></tr></table></figure>


<p>另一种写法</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">Calc</span><span class="hljs-params">(Type a)</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-comment">/* 根据题目的意思计算 */</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Solve</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">double</span> Left, Right;<br>    <span class="hljs-keyword">double</span> mid, midmid;<br>    <span class="hljs-keyword">double</span> mid_value, midmid_value;<br>    Left = MIN; Right = MAX;<br>    <span class="hljs-keyword">while</span> (Left + EPS &lt; Right)<br>    &#123;<br>        mid = (Left + Right) / <span class="hljs-number">2</span>;<br>        midmid = (mid + Right) / <span class="hljs-number">2</span>;<br>        mid_area = <span class="hljs-built_in">Calc</span>(mid);<br>        midmid_area = <span class="hljs-built_in">Calc</span>(midmid);<br>        <span class="hljs-keyword">if</span> (mid_area &gt;= midmid_area) Right = midmid;<br>        <span class="hljs-keyword">else</span> Left = mid;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>


            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/ACM/">ACM</a>
                    
                      <a class="hover-with-bg" href="/tags/%E7%AE%97%E6%B3%95Algorithm/">算法Algorithm</a>
                    
                      <a class="hover-with-bg" href="/tags/%E4%BA%8C%E5%88%86/">二分</a>
                    
                      <a class="hover-with-bg" href="/tags/%E4%B8%89%E5%88%86/">三分</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/04/18/queue/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">queue(队列)</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/04/18/greedy-algorithm/">
                        <span class="hidden-mobile">贪心</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "/local-search.xml";
      $('#local-search-input').on('click', function() {
        searchFunc(path, 'local-search-input', 'local-search-result');
      });
      $('#modalSearch').on('shown.bs.modal', function() {
        $('#local-search-input').focus();
      });
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
